package org.urchr.web.db;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class DBUtil {
	private SessionFactory factory = null;
	protected  AnnotationConfiguration configuration = null;
	private static DBUtil instance = null;



	/**
	 * Constructs new Hibernate Configuration and SessionFactory. 
	 * Generates DB schema into WEB-INF/patents.schema file
	 */
	private DBUtil(){
		try {
			configuration = new AnnotationConfiguration();
			configuration = configuration.configure();
//			SchemaExport se = new SchemaExport(c);
//			se.setOutputFile("db.schema");
//			se.create(true, false);
			factory = configuration.buildSessionFactory();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private Session getSessionPrivate(){
		try {
			return factory.openSession();			
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return null;		
	}

    private static DBUtil getInstance(){
		if(instance==null){
			instance = new DBUtil();
		}
		return instance;
    }

    public static boolean createSchema(){
        try {
            SchemaExport se = new SchemaExport(getInstance().configuration);
//            se.setOutputFile("db.schema");
            se.create(false, true);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean exportSchema(String aFileName){
        try {
            SchemaExport se = new SchemaExport(getInstance().configuration);
            se.setOutputFile(aFileName);
            se.create(true, false);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

	/**
	 * Singleton pattern. Returns current Hibernate session
	 * @return
	 */
	public static Session getSession(){		
        return getInstance().getSessionPrivate();
	}
}
